<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminRole;
use App\Models\AdminMenu;
use App\Helpers\Common;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class AdminRoleController extends BaseController
{
    public function initialize(Request $request)
    {
        parent::initialize($request);

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere[] = ['status', '<>', 90];
        $this->defaultWhere = $defaultWhere;
    }

    /**
     * 权限
     */
    public function getMenus(Request $request)
    {
        $param = $request->all();

        $access = [];
        if (isset($param['id'])) {
            $roleId = $param['id'];
            $access = AdminRole::where('id', $roleId)->get('access')->toArray();
            $access = explode(',', $access[0]['access']);
        }

        $list = [];
        $recursive = function ($parentId) use (&$recursive, &$list, $access) {
            $where = [
                ['parent_id', '=', $parentId],
                ['status', '=', 1]
            ];
            $menus = AdminMenu::where($where)->select('id', 'name as title', 'parent_id')->orderBy('sorting', 'ASC')->get()->toArray();
            foreach ($menus as $key => &$menu) {
                //$menu['spread'] = true; // 节点是否初始展开
                $menu['field'] = 'access[]';
                if (in_array($menu['id'], $access)) {
                    $menu['checked'] = true;
                }

                // 下级菜单
                $menu['children'] = $recursive($menu['id']);
                if ($parentId == 0) {
                    $list[] = $menu;
                }
            }

            return $menus;
        };

        $recursive(0);

        return response()->json($list);
    }

    protected function evalData($request)
    {
        $data = $request->all();
        $data['access'] = implode(',', $data['access']);

        // 去掉_token、文件上传字段file
        unset($data['_token'], $data['s'], $data['file']);

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = explode(' ~ ', $param['range_date']);
            $where[] = ['created_at', '>=', strtolower($rangeDate[0])];
            $where[] = ['created_at', '<=', strtotime($rangeDate[1])];
        }

        return $where;
    }
}
